package com.leslie.hhcommunity.controller;

import com.alibaba.fastjson.JSONObject;
import com.leslie.hhcommunity.entity.Message;
import com.leslie.hhcommunity.entity.Page;
import com.leslie.hhcommunity.entity.User;
import com.leslie.hhcommunity.service.MessageService;
import com.leslie.hhcommunity.service.UserService;
import com.leslie.hhcommunity.util.CommunityConstant;
import com.leslie.hhcommunity.util.CommunityUtil;
import com.leslie.hhcommunity.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

/**
 * @author
 * @PackageName:com.leslie.hhcommunity.controller
 * @ClassnName:MessageController
 * @Description:
 * @Date 2022/1/4  20:54
 */
@Controller
public class MessageController implements CommunityConstant {

	@Autowired
	MessageService messageService;
	@Autowired
	HostHolder hostHolder;
	@Autowired
	UserService userService;

	/**
	 * 查询私信列表
	 *
	 * @param model
	 * @param page
	 * @return
	 */
	@RequestMapping("/letter/list")
	public String getLetterList(Model model, Page page) {

		User user = hostHolder.getUser();

		//分页信息
		page.setLimit(5);
		page.setPath("/letter/list");
		page.setRows(messageService.selectConversationCount(user.getId()));

		//会话列表
		List<Message> conversationList = messageService.selectConversations(user.getId(), page.getOffset(), page.getLimit());
		List<Map<String, Object>> conversations = new ArrayList<>();
		if (conversationList != null) {
			for (Message message : conversationList) {
				Map<String, Object> map = new HashMap<>();
				map.put("conversation", message);
				map.put("letterCount", messageService.selectLetterCount(message.getConversationId()));
				map.put("unreadCount", messageService.selectLetterUnreadCount(user.getId(), message.getConversationId()));
				//消息列表中对方的id
				int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
				map.put("target", userService.findUserById(targetId));
				conversations.add(map);
			}
		}
		model.addAttribute("conversations", conversations);

		// 查询未读消息数量
		int letterUnreadCount = messageService.selectLetterUnreadCount(user.getId(), null);
		model.addAttribute("letterUnreadCount", letterUnreadCount);
		// 查询未读通知数量
		int noticeUnreadCount = messageService.selectNoticeUnreadCount(hostHolder.getUser().getId(), null);
		model.addAttribute("noticeUnreadCount", noticeUnreadCount);
		return "site/letter";
	}

	/**
	 * 查看私信
	 *
	 * @param conversationId
	 * @param page
	 * @return
	 */
	@RequestMapping("/letter/detail/{conversationId}")
	public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model) {
		// 分页信息
		page.setLimit(5);
		page.setPath("/letter/detail/" + conversationId);
		page.setRows(messageService.selectLetterCount(conversationId));

		//私信列表
		List<Message> letterList = messageService.selectLetters(conversationId, page.getOffset(), page.getLimit());
		List<Map<String, Object>> letters = new ArrayList<>();
		if (letterList != null) {
			for (Message message : letterList) {
				Map<String, Object> map = new HashMap<>();
				map.put("letter", message);
				//就是当前登录用户的id
				map.put("fromUser", userService.findUserById(message.getFromId()));
				letters.add(map);
			}
		}
		model.addAttribute("letters", letters);
		// 私信目标
		model.addAttribute("target", getLetterTarget(conversationId));

		// 设置已读
		List<Integer> ids = getLetterIds(letterList);
		if (!ids.isEmpty()) {
			messageService.updateStatus(ids, 1);
		}
		return "site/letter-detail";
	}

	/**
	 * 获取所有未读消息id
	 *
	 * @param letterList
	 * @return
	 */
	private List<Integer> getLetterIds(List<Message> letterList) {
		List<Integer> ids = new ArrayList<>();
		if (letterList != null) {
			for (Message message : letterList) {
				if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {
					ids.add(message.getId());
				}
			}
		}
		return ids;
	}

	/**
	 * 得到私信目标的方法
	 *
	 * @param conversationId
	 * @return
	 */
	private User getLetterTarget(String conversationId) {
		String[] ids = conversationId.split("_");
		int id0 = Integer.parseInt(ids[0]);
		int id1 = Integer.parseInt(ids[1]);
		if (hostHolder.getUser().getId() == id0) {
			return userService.findUserById(id1);
		} else {
			return userService.findUserById(id0);
		}
	}

	/**
	 * 发送私信
	 * @param toName
	 * @param content
	 * @return
	 */
	@RequestMapping(value = "/letter/send", method = RequestMethod.POST)
	@ResponseBody
	public String sendLetter(String toName, String content) {

		User target = userService.selectByName(toName);
		if ((target == null)) {
			return CommunityUtil.getJSONString(1, "目标用户不存在");
		}

		Message message = new Message();
		message.setFromId(hostHolder.getUser().getId());
		message.setToId(target.getId());
		//161_164 id小的在前
		message.setConversationId(
				message.getFromId() < message.getToId()
						? message.getFromId() + "_" + message.getToId()
						: message.getToId() + "_" + message.getFromId());
		message.setContent(content);
		message.setCreateTime(new Date());
		messageService.insertMessage(message);
		return CommunityUtil.getJSONString(0);
	}

	/**
	 * 系统通知列表
	 * @param model
	 * @return
	 */
	@RequestMapping("/notice/list")
	public String getNoticeList(Model model) {
		User user = hostHolder.getUser();

		// 查询评论类通知
		Message message = messageService.selectLatesNotice(user.getId(), TOPIC_COMMENT);
		if (message != null) {
			Map<String, Object> messageVO = new HashMap<>();
			messageVO.put("message", message);

			String content = HtmlUtils.htmlUnescape(message.getContent());
			Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

			messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
			messageVO.put("entityType", data.get("entityType"));
			messageVO.put("entityId", data.get("entityId"));
			messageVO.put("postId", data.get("postId"));

			int count = messageService.selectNoticeCount(user.getId(), TOPIC_COMMENT);
			messageVO.put("count", count);

			int unread = messageService.selectNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
			messageVO.put("unread", unread);

			model.addAttribute("commentNotice", messageVO);
		}

		// 查询点赞类通知
		message = messageService.selectLatesNotice(user.getId(), TOPIC_LIKE);
		if (message != null) {
			Map<String, Object> messageVO = new HashMap<>();
			messageVO.put("message", message);

			String content = HtmlUtils.htmlUnescape(message.getContent());
			Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

			messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
			messageVO.put("entityType", data.get("entityType"));
			messageVO.put("entityId", data.get("entityId"));
			messageVO.put("postId", data.get("postId"));

			int count = messageService.selectNoticeCount(user.getId(), TOPIC_LIKE);
			messageVO.put("count", count);

			int unread = messageService.selectNoticeUnreadCount(user.getId(), TOPIC_LIKE);
			messageVO.put("unread", unread);

			model.addAttribute("likeNotice", messageVO);
		}

		// 查询关注类通知
		message = messageService.selectLatesNotice(user.getId(), TOPIC_FOLLOW);
		if (message != null) {
			Map<String, Object> messageVO = new HashMap<>();
			messageVO.put("message", message);

			String content = HtmlUtils.htmlUnescape(message.getContent());
			Map<String, Object> data = JSONObject.parseObject(content, HashMap.class);

			messageVO.put("user", userService.findUserById((Integer) data.get("userId")));
			messageVO.put("entityType", data.get("entityType"));
			messageVO.put("entityId", data.get("entityId"));

			int count = messageService.selectNoticeCount(user.getId(), TOPIC_FOLLOW);
			messageVO.put("count", count);

			int unread = messageService.selectNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
			messageVO.put("unread", unread);

			model.addAttribute("followNotice", messageVO);
		}
		//查询未读消息数量
		int letterUnreadCount = messageService.selectLetterUnreadCount(hostHolder.getUser().getId(), null);
		model.addAttribute("letterUnreadCount", letterUnreadCount);
		// 查询未读通知数量
		int noticeUnreadCount = messageService.selectNoticeUnreadCount(hostHolder.getUser().getId(), null);
		model.addAttribute("noticeUnreadCount", noticeUnreadCount);
		return "site/notice";
	}


	/**
	 * 去通知详情页面
	 * @param topic
	 * @param page
	 * @param model
	 * @return
	 */
	@RequestMapping("/notice/detail/{topic}")
	public String getNoticesDetail(@PathVariable("topic") String topic, Page page, Model model){
		User user = hostHolder.getUser();
		page.setLimit(5);
		page.setPath("/notice/detail/" + topic);
		page.setRows(messageService.selectNoticeCount(user.getId(), topic));
		List<Message> noticeList = messageService.selectNotices(user.getId(), topic, page.getOffset(), page.getLimit());
		List<Map<String, Object>> noticeVoList = new ArrayList<>();
		if (noticeList != null){
			for (Message notice : noticeList) {
				Map<String, Object> map = new HashMap<>();
				//通知
				map.put("notice", notice);
				//内容
				String content = HtmlUtils.htmlUnescape(notice.getContent());
				Map<String, Object> data = JSONObject.parseObject(content, Map.class);
				map.put("user", userService.findUserById((Integer) data.get("userId")));
				map.put("entityType", data.get("entityType"));
				map.put("entityId", data.get("entityId"));
				map.put("postId", data.get("postId"));
				//发起消息的用户
				map.put("fromUser", userService.findUserById(notice.getFromId()));
				noticeVoList.add(map);
			}
		}
		model.addAttribute("notices", noticeVoList);
		//消息设置已读
		List<Integer> ids = getLetterIds(noticeList);
		if (!ids.isEmpty()){
			messageService.updateStatus(ids, 1);
		}
		return "site/notice-detail";
	}

}
